//
//  MTURLRequest.m
//  MobTimes
//
//  Created by 江山 王 on 4/30/12.
//  Copyright (c) 2012 Finalist. All rights reserved.
//

#import "MTURLRequest.h"

@implementation MTURLRequest

@synthesize delegate = _delegate;
@synthesize urlString = _urlString;
@synthesize timeout = _timeout;
@synthesize conn = _conn;
@synthesize error = _error;
@synthesize responseData = _responseData;

- (id)initWithDelegate:(id)delegateParam {
    if (self = [super init]) {
        _delegate = delegateParam;
        self.timeout = MTURLRequestDefaultTimeout;
        self.conn = nil;
        self.responseData = [[NSMutableData alloc] init];
    }
    return self;
}

- (void)dealloc {
    self.urlString = nil;
    self.error = nil;
    self.conn = nil;
    self.responseData = nil;
    [super dealloc];
}

#pragma mark - Public methods implementation

- (void)sendAsynchrously {
    if (!_delegate) {
        return;
    }
    if (!_urlString) {
        NSError *_tempError = [NSError errorWithDomain:MTErrorDomain code:0 userInfo:[NSDictionary dictionaryWithObject:@"_urlString is nil." forKey:NSLocalizedDescriptionKey]];
        if ([_delegate respondsToSelector:@selector(request:didFailLoadWithError:)]) {
            [_delegate request:self didFailLoadWithError:_tempError];
        }
        return;
    }
    
    NSURL *_url = [NSURL URLWithString:self.urlString];
    NSURLRequest *_urlRequest = [[NSURLRequest alloc] initWithURL:_url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:self.timeout];
    
    _conn = [[NSURLConnection alloc] initWithRequest:_urlRequest delegate:self startImmediately:NO];;
        
    [_conn scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    [_conn start];
    
//    [_urlRequest release];
//    _urlRequest = nil;
}

- (void)cancel {
    [self.conn cancel];
    if ([_delegate respondsToSelector:@selector(requestDidCancelLoad:)]) {
        [_delegate requestDidCancelLoad:self];
    }
}

#pragma mark - NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    MTDebugLog(MT_String("ERROR: Failed to load data with comming msg: %@"), error.description);
    self.error = error;
}

#pragma mark - NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSHTTPURLResponse *_response = (NSHTTPURLResponse *)response;
    MTDebugLog(MT_String("INFO: Did receive response with status code : %d"), _response.statusCode);
    if ([_delegate respondsToSelector:@selector(requestDidStartLoad:)]) {
        [_delegate requestDidStartLoad:self];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    MTDebugLog(MT_String("INFO: Did receive data."));
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *_responseDataString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
    MTDebugLog(MT_String("INFO: Did finish to load data: %@"), _responseDataString);
    [_responseDataString release];
    _responseDataString = nil;
    if (!_error) {
        if ([_delegate respondsToSelector:@selector(requestDidFinishLoad:)]) {
            MTDebugLog(MT_String("INFO: Call model's requestDidFinishLoad."));
            [_delegate requestDidFinishLoad:self];
        }
    } else {
        if ([_delegate respondsToSelector:@selector(request:didFailLoadWithError:)]) {
            MTDebugLog(MT_String("ERROR: Failed to load data"));
            [_delegate request:self didFailLoadWithError:self.error];
        }
    }
}

@end